#include "cart.h"
#include "ui_cart.h"
#include <QSqlQuery>
#include <QMessageBox>
#include <QFont>
#include <QPushButton>
#include <QInputDialog>

Cart::Cart(QWidget *parent, int userId)
    : QDialog(parent),
      ui(new Ui::Cart),
      m_userId(userId)
{
    ui->setupUi(this);

    // 替代方案：手动断开所有按钮连接
    disconnectAllButtons();

    setWindowTitle("购物车");

    m_db = QSqlDatabase::addDatabase("QSQLITE", "cart_connection");
    m_db.setDatabaseName("flower_shop.db");

    if (!m_db.open()) {
        QMessageBox::critical(this, "错误", "无法连接数据库: " + m_db.lastError().text());
    }

    ui->totalPriceLabel->setFont(QFont("Microsoft YaHei", 14, QFont::Bold));
    ui->addToCartButton->setVisible(false);

    // 显式手动连接所有按钮
    //connect(ui->backButton, &QPushButton::clicked, this, &Cart::on_backButton_clicked);
    connect(ui->removeFromCartButton, &QPushButton::clicked, this, &Cart::on_removeFromCartButton_clicked);
    connect(ui->clearCartButton, &QPushButton::clicked, this, &Cart::on_clearCartButton_clicked);
    connect(ui->calculateTotalButton, &QPushButton::clicked, this, &Cart::updateTotalPrice);
    connect(ui->placeOrderButton, &QPushButton::clicked, this, &Cart::on_placeOrderButton_clicked);
    connect(ui->setAddressButton, &QPushButton::clicked, this, &Cart::on_setAddressButton_clicked);
    loadCartItems();
}

void Cart::disconnectAllButtons()
{
    QList<QPushButton*> buttons = findChildren<QPushButton*>();
    foreach (QPushButton* btn, buttons) {
        disconnect(btn, &QPushButton::clicked, 0, 0);
    }
}

Cart::~Cart()
{
    if(m_db.isOpen()) {
        m_db.close();
    }
    delete ui;
}

void Cart::loadCartItems()
{
    ui->cartItemsList->clear();

    QSqlQuery query(m_db);
    query.prepare("SELECT c.cart_id, p.name, p.price, c.quantity FROM Cart c "
                 "JOIN products p ON c.product_id = p.product_id "
                 "WHERE c.user_id = ?");
    query.addBindValue(m_userId);

    if (query.exec()) {
        while (query.next()) {
            int cartId = query.value(0).toInt();
            QString name = query.value(1).toString();
            double price = query.value(2).toDouble();
            int quantity = query.value(3).toInt();

            QListWidgetItem *item = new QListWidgetItem(
                QString("%1 - ¥%2 × %3").arg(name).arg(price, 0, 'f', 2).arg(quantity));
            item->setData(Qt::UserRole, cartId); // 存储cart_id以便后续操作
            item->setFont(QFont("Microsoft YaHei", 12));
            ui->cartItemsList->addItem(item);
        }
    }
    updateTotalPrice();
}

void Cart::updateTotalPrice()
{
    QSqlQuery query(m_db);
    query.prepare("SELECT SUM(p.price * c.quantity) FROM Cart c "
                 "JOIN products p ON c.product_id = p.product_id "
                 "WHERE c.user_id = ?");
    query.addBindValue(m_userId);

    if (query.exec() && query.next()) {
        double total = query.value(0).toDouble();
        ui->totalPriceLabel->setText(QString("总价: ¥%1").arg(total, 0, 'f', 2));
    } else {
        ui->totalPriceLabel->setText("总价: ¥0.00");
    }
}

void Cart::on_backButton_clicked()
{
    this->accept(); // 关闭购物车窗口
}


QString Cart::getUsername()
{
    QSqlQuery query(m_db);
    query.prepare("SELECT username FROM login_users WHERE user_id = ?");
    query.addBindValue(m_userId);

    if (!query.exec()) {
        QMessageBox::critical(this, "错误",
            QString("获取用户名失败: %1\n执行的SQL: %2")
                .arg(query.lastError().text())
                .arg(query.lastQuery()));
        return QString();
    }

    if (query.next()) {
        return query.value(0).toString();
    } else {
        QMessageBox::critical(this, "错误",
            QString("用户ID %1 不存在").arg(m_userId));
        return QString();
    }
}

QString Cart::getUserAddress() const
{
    QSqlQuery query(m_db);
    query.prepare("SELECT address FROM user_address WHERE user_id = ? LIMIT 1");
    query.addBindValue(m_userId);

    if (query.exec() && query.next()) {
        return query.value(0).toString();
    }

    // 如果没有地址记录，返回空字符串
    return QString();
}

// 在 cart.cpp 的 on_placeOrderButton_clicked 方法中修改
void Cart::on_placeOrderButton_clicked()
{
    // 检查购物车是否为空
    if (ui->cartItemsList->count() == 0) {
        QMessageBox::warning(this, "警告", "购物车为空，无法结算!");
        return;
    }

    // 获取用户地址和用户名
    QString userAddress = getUserAddress();
    if (userAddress.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先设置收货地址!");
        return;
    }
    QString username = getUsername();
    if (username.isEmpty()) {
            QMessageBox::critical(this, "错误", "无法获取用户名");
            return;
        }



    // 计算总价
    double total = 0.0;
    QSqlQuery query(m_db);
    query.prepare("SELECT SUM(p.price * c.quantity) FROM Cart c "
                 "JOIN products p ON c.product_id = p.product_id "
                 "WHERE c.user_id = ?");
    query.addBindValue(m_userId);

    if (!query.exec() || !query.next()) {
        QMessageBox::critical(this, "错误", "无法计算总价: " + query.lastError().text());
        return;
    }
    total = query.value(0).toDouble();

    // 创建订单（根据实际表结构）
    query.prepare("INSERT INTO Orders (user_id, total_price, create_time, status, address) "
                 "VALUES (?, ?, datetime('now'), ?, ?)");
    query.addBindValue(m_userId);
    query.addBindValue(total);
    query.addBindValue("待支付"); // 订单状态
    query.addBindValue(userAddress);

    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "创建订单失败: " + query.lastError().text());
        return;
    }

    int orderId = query.lastInsertId().toInt();

    // 添加订单详情
    query.prepare("INSERT INTO OrderDetails (order_id, product_id, quantity) "
                 "SELECT ?, c.product_id, c.quantity FROM Cart c "
                 "WHERE c.user_id = ?");
    query.addBindValue(orderId);
    query.addBindValue(m_userId);

    if (!query.exec()) {
        QMessageBox::critical(this, "错误", "添加订单详情失败: " + query.lastError().text());
        return;
    }

    // 清空购物车
    query.prepare("DELETE FROM Cart WHERE user_id = ?");
    query.addBindValue(m_userId);

    if (query.exec()) {
        QMessageBox::information(this, "结算成功", QString("订单 #%1 已创建!").arg(orderId));
        loadCartItems();
    } else {
        QMessageBox::critical(this, "错误", "清空购物车失败: " + query.lastError().text());
    }
}




// 在 cart.cpp 中添加
void Cart::on_setAddressButton_clicked()
{
    bool ok;
    QString address = QInputDialog::getText(this, "设置收货地址",
                                          "请输入收货地址:",
                                          QLineEdit::Normal,
                                          "", &ok);
    if (ok && !address.isEmpty()) {
        QSqlQuery query(m_db);
        query.prepare("INSERT OR REPLACE INTO user_address (user_id, address) "
                     "VALUES (?, ?)");
        query.addBindValue(m_userId);
        query.addBindValue(address);

        if (!query.exec()) {
            QMessageBox::critical(this, "错误", "保存地址失败: " + query.lastError().text());
        }
    }
}
void Cart::on_removeFromCartButton_clicked()
{
    QListWidgetItem *item = ui->cartItemsList->currentItem();
    if (!item) {
        QMessageBox::warning(this, "警告", "请先选择要删除的商品");
        return;
    }

    int cartId = item->data(Qt::UserRole).toInt();

    QSqlQuery query(m_db);
    query.prepare("DELETE FROM Cart WHERE cart_id = ?");
    query.addBindValue(cartId);

    if (query.exec()) {
        delete ui->cartItemsList->takeItem(ui->cartItemsList->row(item));
        updateTotalPrice();
        QMessageBox::information(this, "成功", "商品已从购物车删除!");
    } else {
        QMessageBox::critical(this, "错误", "删除失败: " + query.lastError().text());
    }
}

void Cart::on_clearCartButton_clicked()
{
    if (ui->cartItemsList->count() == 0) {
        QMessageBox::warning(this, "警告", "购物车已经是空的!");
        return;
    }

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "确认", "确定要清空购物车吗?",
                                QMessageBox::Yes|QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        QSqlQuery query(m_db);
        query.prepare("DELETE FROM Cart WHERE user_id = ?");
        query.addBindValue(m_userId);

        if (query.exec()) {
            ui->cartItemsList->clear();
            updateTotalPrice();
            QMessageBox::information(this, "成功", "购物车已清空!");
        } else {
            QMessageBox::critical(this, "错误", "清空购物车失败: " + query.lastError().text());
        }
    }
}
